﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetAccess.Server;
using GalaSoft.MvvmLight.Messaging;

namespace SimpleChat.Network
{
    class Server : ServerLayer<ChatConnexion>
    {
        public IMessenger MessengerInstance { get; private set; }

        private readonly string _appid;
        private readonly int _serviceDiscoveryPort;
        private readonly int _serviceTCPPort;
        private string _serverName;
        private string _serverPassword;

        public Server(IMessenger messengerInstance, string serverName, string serverPassword)
        {
            _appid = Properties.Settings.Default.ApplicationIdentifier;
            _serviceDiscoveryPort = Properties.Settings.Default.DiscoveryPort;
            _serviceTCPPort = Properties.Settings.Default.ServiceTCPPort;
            _serverName = serverName;
            _serverPassword = serverPassword;
            MessengerInstance = messengerInstance;
        }

        public void Start()
        {
            Start(new ServerConfiguration(_appid, _serverName, null, _serviceTCPPort)
            {
                IsEnableServiceDiscovery = true,
                ServiceDiscoveryPort = _serviceDiscoveryPort
            });
        }

        public override void OnStarted()
        {
            MessengerInstance.Send(new ChatContentMessage(String.Format("Server {0} started !", _serverName), ChatContentMessage.MessageType.System));
        }

        public override void OnStopped()
        {
            MessengerInstance.Send(new ChatContentMessage(String.Format("Server {0} stopped !", _serverName), ChatContentMessage.MessageType.System));
        }

        protected override void OnClientConnected(ChatConnexion client)
        {
            MessengerInstance.Send(new ChatContentMessage(String.Format("Incomming client"), ChatContentMessage.MessageType.System));
        }

        protected override void OnClientDisconnected(ChatConnexion client)
        {
            MessengerInstance.Send(new ChatContentMessage(String.Format("Client leave"), ChatContentMessage.MessageType.System));
        }

        public bool CheckPassword(string password)
        {
            return String.IsNullOrEmpty(_serverPassword) ||
                   password.Equals(_serverPassword, StringComparison.InvariantCulture);
        }

        public bool CheckUsername(string username)
        {
            return Clients.All(c => c.Value.Username != username);
        }

        public Dictionary<int, string> GetAllUsers()
        {
            return Clients.ToDictionary(c => c.Key, c => c.Value.Username);
        }
    }
}
